#!/usr/bin/env python
"""Some code for testing blogger api"""
import sys

from gdata import service
import gdata
import atom
import getpass
from passwordcache import PasswordCache

class Blog(object):
    def __init__(self, blogger, entry):
        self._blogger = blogger
        self._entry = entry

    @property
    def title(self):
        return self._entry.title.text

    @property
    def tags(self):
        return [category.term for category in self._entry.category]

    @property
    def id(self):
        try:
            return self._id
        except AttributeError:
            self._id = self._entry.GetSelfLink().href.split("/")[-1]
            return self._id

    def createPost(self, title, content, author=None, categories=None, is_draft=True):
        """Creates a post, returns the post id"""
        post = gdata.GDataEntry()
        post.title = atom.Title(title_type='xhtml', text=title)
        post.content = atom.Content(content_type='html', text=content)

        if author:
            post.author.append(atom.Author(atom.Name(text=author)))

        if categories:
            for cat in categories:
                post.category.append(atom.Category(term=cat, scheme="http://www.blogger.com/atom/ns#"))

        if is_draft:
            control = atom.Control()
            control.draft = atom.Draft(text='yes')
            post.control = control

        return self._blogger.Post(post, '/feeds/%s/posts/default' % self.id)

    def getPosts(self):
      return self._blogger.GetFeed('/feeds/' + self.id + '/posts/default')

    def getPost(self, id):
        return self._blogger.GetEntry('/feeds/%s/posts/default/%s' % (self.id, id))

class Post(object):
    def __init__(self, blogger, post):
        self._blogger = blogger
        self._post = post

    @apply
    def title():
        """Post title"""
        def fget(self):
            return self._post.title.text
        def fset(self, new_title):
            self._post.title = atom.Title('xhtml', new_title)
        return property(**locals())

    @property
    def tags(self):
        return [category.term for category in self._post.category]

    @apply
    def content():
        """Post content"""
        def fget(self):
            return self._post.content.text
        def fset(self, value):
            self._post.content = atom.Content('xhtml', new_title)
            self._post.content.text = value
        return property(**locals())

    @property
    def id(self):
        return self.self_link.split("/")[-1]

    @property
    def is_draft(self):
        try:
            control = self._post.control.draft.text
            return control=='yes'
        except AttributeError:
            return False

    @property
    def edit_link(self):
        """Get the URL to edit this post"""
        return self._post.GetEditLink().href

    @property
    def self_link(self):
        """Get the URL to uniquely identify this post"""
        return self._post.GetSelfLink().href

    @property
    def public_link(self):
        """Get the public URL for this post"""
        return self._post.GetHtmlLink().href

    def delete(self):
        """Delete this post"""
        self._blogger.Delete(self.edit_link)

    def update(self):
        """Save changes to this post"""
        self._blogger.Put(self._post, self.edit_link)

    def publish(self):
        """Publish a draft post"""
        if not self.is_draft:
            raise ValueError('post %d is not in draft mode' % self.id)
        self._post.control.draft = atom.Draft(text='no')
        self.update()

        
class Blogger(object):
    """Wrapper for the blogger gdata api"""
    def __init__(self, user, password):
        self.blogger = blogger = service.GDataService(user, password)
        blogger.source = 'test-app'
        blogger.service = 'blogger'
        blogger.server = 'www.blogger.com'
        blogger.ProgrammaticLogin()

    def Post(self, entry, url):
        return Post(self, self.blogger.Post(entry, url))

    def GetFeed(self, url):
        for entry in self.blogger.GetFeed(url).entry:
            yield Post(self, entry)

    def GetEntry(self, url):
        return Post(self, self.blogger.GetEntry(url))

    def Delete(self, url):
        return self.blogger.Delete(url)

    def Put(self, entry, url):
        return self.blogger.Put(entry, url)

    def findBlog(self, title=None, uri=None):
        """Find a blog by its title or public uri"""
        query = service.Query()
        query.feed = '/feeds/default/blogs'
        feed = self.blogger.Get(query.ToUri())

        def match(entry):
            if title is not None:
                if title.strip().lower()==entry.title.text.strip().lower():
                    return True
            if uri is not None:
                if entry.GetHtmlLink().href.rstrip('/')==uri.rstrip('/'):
                    return True
            return False

        for entry in feed.entry:
            if match(entry):
                return Blog(self, entry)

        return None, None, None
        
    def getBlogs(self):
        query = service.Query()
        query.feed = '/feeds/default/blogs'
        feed = self.blogger.Get(query.ToUri())
#         for e in feed.entry:
#             print e

        print feed.title.text
        self.blogs = []
        import pdb;pdb.set_trace()
        for entry in feed.entry:
            title = entry.title.text
            tags = [category.term for category in entry.category]
            id = entry.GetSelfLink().href.split("/")[-1]
            print id, title, tags
            self.blogs.append((id, title, tags))

        return self.blogs

    def PrintAllPosts(self, blog_id):
      feed = self.blogger.GetFeed('/feeds/' + blog_id + '/posts/default')

      print feed.title.text
      import pdb; pdb.set_trace()
      for entry in feed.entry:
        print "\t" + entry.title.text
        print "\t" + repr(entry.content.text)[:75]
        print "\t" + entry.updated.text
      print
      print entry

if __name__=='__main__':
    store = PasswordCache()
    user = sys.argv[1]
    password = store.get('http://www.blogspot.com', user, getpass.getpass, cache=True)
    
    b = Blogger(sys.argv[1], password)
    blog = b.findBlog(uri='http://kupuguy-test.blogspot.com')
    print blog.id, blog.title, blog.tags
    #blogs = b.getBlogs()
    for post in blog.getPosts():
        print post.title
        print post.self_link
        print post.edit_link
        print post.content
        print "Draft" if post.is_draft else "Published"
        print

        
